package com.captain.special.二叉树;

import com.captain.leetcode.TreeNode;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/4/22 15:53
 */
public class 平衡二叉树110 {

    public boolean isBalanced(TreeNode root) {
        //平衡二叉树: 每个节点的左右子树的高度差的绝对值不超过2
        //TODO 求树的高度
        return recur(root) != -1;
    }

    private int recur(TreeNode node) {
        if (node == null) return 0;
        int leftLen = recur(node.left);
        if (leftLen == -1) return -1;
        int rightLen = recur(node.right);
        if (rightLen == -1) return -1;
        return Math.abs(leftLen - rightLen) >= 2 ? -1 : Math.max(leftLen, rightLen) + 1;
    }
}
